package com.xc.quickstart.common.event;

import com.alibaba.excel.util.DateUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 系统告警延迟队列事件
 *
 * @author yinyansheng
 */
@Data
@EqualsAndHashCode
public class ExceptionDelayQueueEvent implements Delayed {

    public ExceptionDelayQueueEvent(String className) {
        this.className = className;
        this.title = className;
        this.alarmCount = 1;
        this.alarmTime = getLatelyTime(new Date());
    }

    public ExceptionDelayQueueEvent(String className, String title, String msg) {
        this.className = className;
        this.title = title;
        this.msg = msg;
        this.alarmCount = 1;
        this.alarmTime = getLatelyTime(new Date());
    }

    private String className;

    @EqualsAndHashCode.Exclude
    private String title;

    @EqualsAndHashCode.Exclude
    private Integer alarmCount;

    @EqualsAndHashCode.Exclude
    private long alarmTime;

    @EqualsAndHashCode.Exclude
    private String msg;

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.alarmTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    public static long getLatelyTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MINUTE, (calendar.get(Calendar.MINUTE)) / 10 * 10);
        calendar.set(Calendar.SECOND, 0);
        calendar.add(Calendar.MINUTE, 10);
        Date late = calendar.getTime();
        return late.getTime();
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(getLatelyTime(DateUtils.parseDate("2021-01-26 16:00:00")));
        System.out.println(getLatelyTime(DateUtils.parseDate("2021-01-26 16:01:00")));
        System.out.println(getLatelyTime(DateUtils.parseDate("2021-01-26 16:10:00")));
        System.out.println(getLatelyTime(DateUtils.parseDate("2021-01-26 16:59:00")));
    }
}
